﻿using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using IEx.Common;
using IEx.Model.Partials;
using IEx.Utilities;

namespace IEx.ParserBuilder.Lamchame
{
    public class LamchameParser : IHtmlParser
    {
        public void Parse(SourceItem item, string html, Action<Model.Partials.Announcement> attachResultItem, Action<SourceItem> attachNewItemSource)
        {
            try
            {
                string threadListId = "id=\"threadlist\"";
                string navpopupId = "id=\"forumdisplay_navpopup\"";
                string remainHtml = Utility.GetHtmlBody(html, threadListId, navpopupId);
                List<Announcement> detectedAnnouncements = new List<Announcement>();
                Uri newUri = Utility.CreateNewUriForNextPage(item.Url, 1);

                if (!string.IsNullOrEmpty(remainHtml))
                {
                    Regex regexLiTags = new Regex("<li class=\"threadbit .*?\" id=\".*?\">.*?</li>");
                    MatchCollection mColLiTags = regexLiTags.Matches(remainHtml);

                    for (int i = 0; i < mColLiTags.Count; i++)
                    {
                        string threadTitle = string.Empty;
                        string threadLinkDetail = string.Empty;
                        string userName = string.Empty;
                        string userLinkDetail = string.Empty;
                        string postContent = string.Empty;
                        string dateTime = string.Empty;
                        DateTime postDate = DateTime.MinValue;

                        string threadContent = mColLiTags[i].Value.Trim();
                        threadContent = string.Join(string.Empty, Regex.Split(threadContent, @"(?:\r\n|\n|\r|\t)"));

                        Regex regTitleTopic = new Regex("<a class=\"title\" .*?>.*?</a>");
                        Match mTitleTopic = regTitleTopic.Match(threadContent);
                        if (mTitleTopic.Success)
                        {
                            string titleTopicHtml = mTitleTopic.Value;
                            threadTitle = RegexUtility.ExtractTextFromHtmlTag(titleTopicHtml);
                            string href = RegexUtility.ExtractHyperlink(titleTopicHtml);
                            threadLinkDetail = Utility.RemoveQueryStringByKey(new Uri(newUri, href).ToString(), "s");
                        }

                        Regex regUserName = new Regex("<span class=\"label\">.*?</span>");
                        Match mUserName = regUserName.Match(threadContent);
                        if (mUserName.Success)
                        {
                            string userNameHtml = mUserName.Value;
                            userName = RegexUtility.ExtractTextFromHtmlTag(userNameHtml);
                            string href = RegexUtility.ExtractHyperlink(userNameHtml);
                            userLinkDetail = Utility.RemoveQueryStringByKey(new Uri(newUri, href).ToString(), "s");
                        }

                        Regex regPostContent = new Regex(@"(?<=\btitle="")[^""]*");
                        MatchCollection mPostContent = regPostContent.Matches(threadContent);
                        for (int j = 0; j < mPostContent.Count; j++)
                        {
                            if (mPostContent[0].Success)
                            {
                                string postContentHtml = mPostContent[0].Value;
                                postContent = postContentHtml;
                                break;
                            }
                        }


                        //Extract comment of this topic
                        List<Comment> comments = new List<Comment>();
                        Utility.ExtractComments(threadLinkDetail, item, ref comments);

                        //Add Announcement to detected announcement
                        if (!string.IsNullOrEmpty(threadTitle) && !string.IsNullOrEmpty(postContent))
                        {
                            Announcement ann = new Announcement();
                            ann.Title = threadTitle;
                            ann.DateTime = postDate;
                            ann.DateNumberic = long.Parse(
                                            postDate.ToString("yyyyMMddHHmmss"));
                            ann.SocialNetwork.ScreenName = userName;
                            ann.Message = postContent;
                            ann.SocialNetwork.Comments = comments;
                            ann.SocialNetwork.AccountLink = userLinkDetail;
                            ann.Attachment = false;
                            ann.InsertedDate = DateTime.Now;
                            ann.LangId = item.LangId;
                            ann.SourceId = item.SourceId;
                            ann.SourceCode = item.SourceCode;
                            detectedAnnouncements.Add(ann);
                        }
                    }
                    //Extract url for next page
                    Regex regNextPage = new Regex("<span class=\"selected\">.*?</span>(?<span>.*?</span>)");
                    Match mNextPage = regNextPage.Match(remainHtml);
                    if (mNextPage.Success)
                    {
                        string nextPageHtml = mNextPage.Value;
                        string link = RegexUtility.ExtractHyperlink(nextPageHtml);
                        if (!string.IsNullOrEmpty(link))
                            item.Url = Utility.RemoveQueryStringByKey(new Uri(newUri, link).ToString(), "s");
                    }
                }

                // check if has next page 
                // next page counts as a new request, so it needed insert into request queue

                if (Utility.CheckNextPage(html))
                {
                    SourceItem nItem = new SourceItem(item.Url, item.LangId, item.SourceCode, item.SearchCode, item.SourceId, item.DateTimeFormat);
                    if (!string.IsNullOrEmpty(item.RequestBuilderType))
                        nItem.RequestBuilderType = item.RequestBuilderType;

                    if (!string.IsNullOrEmpty(item.HtmlParserType))
                        nItem.HtmlParserType = item.HtmlParserType;

                    nItem.PrevResponseHtml = html;
                    attachNewItemSource(nItem);
                }

                // insert into download queue when no error in parsing
                foreach (Announcement ann in detectedAnnouncements)
                {
                    attachResultItem(ann);
                }

                // if this request is fail request in previous scanning, 
                // remove it when success in current scanning
                if (item.FailId > 0)
                    Utility.DeleteFailRequests(item.FailId);
            }
            catch (Exception ex)
            {
                // if has an error, save fail request to next time scanning
                if (item.FailId == 0)
                {
                    item.FailId = DateTime.Now.Ticks;
                    Utility.SaveFailRequests(item);
                }

                // then write log
                string message = string.Format(@"
            Company code:   {0}
            HTML Parsing:   Fail
            Request URL:    {1}
            Search key:     {2}", item.SourceCode, item.Url, item.SearchCode);
                Logger.WriteError(message, ex);
            }
        }
    }
}
